package com.tanguy.user.db

import android.content.Context
import com.tanguy.user.bean.PlaceShowBean
import org.jetbrains.anko.db.*

/**
 * Created by zhangyujiu on 2017/8/8.
 */
object AdHistoryManager {
    /**
     * 判断表中是否含有相同数据
     */
    fun isHasSameData(context: Context, name: String): Boolean {
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        val rowParser = classParser<PlaceShowBean>()
        val data = db.select("AdHistory").whereArgs("name={name}", "name" to name).parseList(rowParser)
        return data.isNotEmpty()
    }

    /**
     * 保存地址信息
     */
    fun saveLocation(context: Context, tip: PlaceShowBean, cityCode: String) {
        if (isHasSameData(context,tip.name))return
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.writableDatabase

        db.insert("AdHistory",
                "name" to tip.name,
                "address" to tip.address,
                "latitude" to tip.latitude,
                "longitude" to tip.longitude,
                "adcode" to cityCode
        )
    }

    /**
     * 加载本地数据
     */
    fun getLocations(context: Context, limit: Int,code:String): List<PlaceShowBean> {
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        val rowParser = classParser<PlaceShowBean>()
        val data = db.select("AdHistory").whereArgs("adcode={adcode}", "adcode" to code).orderBy("id", SqlOrderDirection.DESC).limit(limit).parseList(rowParser)
        return data
    }

    /**
     * 清空数据
     */
    fun clearTable(context: Context){
        val database = MyDatabaseOpenHelper.getInstance(context)
        val db = database.readableDatabase
        db.delete("AdHistory")
    }
}